﻿$(function () {
    toastr.options.positionClass = 'toast-bottom-center';
    var vm = new Vue({
        el: '#app',
        data: {
            // 角色与权限
            depDeviceTypePermission: true, // 能进到本页面，就是true
            depDeviceTypeAddPermission: false,
            depDeviceTypeRemovePermission: false,
            depDeviceTypeCreatePermission: false,
            multiDepartmentPermission: false,

            // 主页面
            filterName: '',
            createDialogVisible: false, // 创建用户对话框，是否显示
            addCurrentDialogVisible: false,// 将现有用户添加到科室
            tableData: [],
            formLabelWidth: '80px',
            department: null,   // 当前科室
            treeData: [],
            depCurrentPage: 1,
            depDeviceTypeTotalCount: 0,
            depPageSize: 10,
            depDeviceTypeTotal: 0,
            depSelectedDeviceTypes: [],


            // 添加现有对话框
            systemDeviceTypes: [],
            filterSystemDeviceName: '',
            systemDeviceTypesTotal: 0,
            systemPageSize: 10,
            systemCurrentPage: 1,
            systgemSelectedDeviceTypes: [],


            deviceType: {
                name: null,
                modality: null,
                code: null,
                outerCode: null,
                isActive: true,
            },

            defaultProps: {     // 科室和tree-node对象的映射
                label: 'name',
                children: 'children'
            },

            // 验证规则
            rules: {
                name: [
                    { required: true, message: '请输入名称', trigger: 'blur' }
                ],
                code: [
                    { required: true, message: '请输入用户编号', trigger: 'blur' }
                ],
                outerCode: [
                    { required: true, message: '请输入外部编号', trigger: 'blur' }
                ]
            }
        },
        computed: {
            tableShow: function () {
                var vm = this;
                if ((vm.treeData[0] && vm.treeData[0].children.length > 0) || vm.department) {
                    return true;
                }
                return false;
            }
        },
        methods: {

            onOuterCodeChange(val) {
                const vm = this;
                vm.deviceType.code = val;
            },

            depSearch() {
                var vm = this;
                vm.depCurrentPage = 1;
                vm.loadDepDeviceTypes
            },

            // 科室用户当前页改变
            depCurrentPageChange(val) {
                var vm = this;
                vm.depCurrentPage = val;
                vm.loadDepDeviceTypes(vm.department.id);
            },

            // 科室用户，每页数量改变
            depPageSizeChange(val) {
                var vm = this;
                vm.depPageSize = val;
                vm.depCurrentPage = 1;
                vm.loadDepDeviceTypes(vm.department.id);
            },

            // 科室选中用户改变
            depDeviceTypeSelectionChange(val) {
                var vm = this;
                vm.depSelectedDeviceTypes = val;
            },

            // 加载当前科室下用户
            loadTableData() {
                var vm = this;
                if (vm.multiDepartmentPermission && vm.treeData[0].children.length > 0) { // admin 角色下，有科室
                    vm.department = vm.treeData[0].children[0]; // 默认加载tree中的第一个科室的用户情况
                    vm.loadDepDeviceTypes(vm.department.id);
                }
                else if (vm.multiDepartmentPermission && vm.treeData[0].children.length === 0) { // admin角色下，系统中还没创建任何科室
                    // 提示系统还没有任何科
                }
                else if (!vm.multiDepartmentPermission) { // 必然时是科室用户，而且必然是已经登录了某个科室，而且已经加载了科室
                    // 根据登录科室加载用户
                    vm.loadDepDeviceTypes(vm.department.id);
                }
            },

            // 加载科室设备类型列表
            loadDepDeviceTypes(id) {
                var vm = this;
                abp.ajax({
                    type: 'GET',
                    url: `/api/depart-device-type/get-dep-device-types?id=${vm.department.id}&filterName=${vm.filterName}&page=${vm.depCurrentPage}&pageSize=${vm.depPageSize}`
                }).then(res => {
                    if (res.code === 0) {
                        vm.tableData = res.data.deviceTypes;
                        vm.depDeviceTypeTotal = res.data.totalCount;
                    }
                });
            },



            // 系统用户列表，每页数量改变
            systemPageSizeChange(val) {
                var vm = this;
                vm.systemPageSize = val;
                vm.systemCurrentPage = 1;
                vm.loadSystemDeviceTypes();
            },

            // 系统用户列表，当前页改变
            systemCurrentPageChange(val) {
                var vm = this;
                vm.systemCurrentPage = val;
                vm.loadSystemDeviceTypes();
            },

            // 查询系统的
            systemSearch() {
                var vm = this;
                vm.systemCurrentPage = 1;
                vm.loadSystemDeviceTypes();
            },

            // 选中的系统用户改变
            systemSelectedChange(val) {
                var vm = this;
                vm.systgemSelectedDeviceTypes = val;
            },

            loadSystemDeviceTypes() {
                var vm = this;
                abp.ajax({
                    type: 'GET',
                    url: `/api/depart-device-type/get-system-device-types?depId=${vm.department.id}&filterName=${vm.filterSystemDeviceName}&page=${vm.systemCurrentPage}&pageSize=${vm.systemPageSize}`
                }).then((res) => {
                    if (res.code == 0) {
                        vm.systemDeviceTypes = res.data.deviceTypes;
                        vm.systemDeviceTypesTotal = res.data.totalCount;
                    }
                });
            },

            // 打开创建用户窗口
            showCreate() {
                var vm = this;
                vm.createDialogVisible = true;
            },

            // 新建提交
            submitCreate() {
                var vm = this;
                vm.$refs['creatDeviceTypeForm'].validate((vaild) => {
                    if (vaild) {
                        abp.ajax({
                            type: 'post',
                            url: `/api/depart-device-type/submit-create?depId=${vm.department.id}`,
                            data: JSON.stringify(vm.deviceType)
                        }).then(res => {
                            if (res.code == 0) {
                                vm.resetCreateForm();
                                vm.loadDepDeviceTypes();
                                abp.notify.success(res.msg);
                            }
                            else {
                                abp.message.error(res.msg);
                            }
                        });
                    }
                });

            },

            // 打开添加现有用户窗口
            showAdd() {
                var vm = this;
                vm.addCurrentDialogVisible = true;
                vm.loadSystemDeviceTypes();
            },

            // 关闭添加对话框时
            closeAddDialog() {
                var vm = this;
                vm.filterSystemUserName = '';
                vm.addCurrentDialogVisible = false;
                vm.systemDeviceTypesTotal = 0;
                vm.systemCurrentPage = 1;
                vm.systgemSelectedDeviceTypes = [];
            },

            // 加载"科室列表(Admin角色)" 和 当前科室(无admin角色，有DepartmentUser权限)
            loadTreeData() {
                var vm = this;
                return new Promise(resolve => {
                    if (vm.multiDepartmentPermission) { // 如果有管理员角色（multiDepartmentPermission只在admin角色中才有）
                        abp.ajax({
                            type: "GET",
                            url: "/api/department-user/get-tree-data"
                        }).then((res) => {
                            if (res.code === 0) {
                                vm.treeData = res.data;
                                resolve();
                            }
                        });
                    }
                    else if (!vm.multiDepartmentPermission) { // 科室用户
                        // 获取当前登录科室
                        abp.ajax({
                            type: "GET",
                            url: "/api/department-user/get-current-user-department"
                        }).then(res => {
                            vm.department = res;
                            resolve();
                        });
                    }

                });
            },

            // 向科室添加设备类型   
            addDeviceTypeToDepartment() {
                var vm = this;
                if (vm.systgemSelectedDeviceTypes.length > 0) {
                    abp.ajax({
                        type: 'POST',
                        url: `/api/depart-device-type/add-to-department?depId=${vm.department.id}`,
                        data: JSON.stringify(vm.systgemSelectedDeviceTypes)
                    }).then((res) => {
                        if (res.code === 0) {
                            vm.closeAddDialog();
                            abp.notify.success(res.msg);
                            vm.loadDepDeviceTypes(vm.department.id);
                        }
                    });
                }
                else {
                    abp.notify.error('无选中用户，请先选择用户。')
                }
            },

            // 将当前用户从当前科室中移除
            removeDeviceType() {
                var vm = this;
                if (vm.depSelectedDeviceTypes.length > 0) {
                    abp.message.confirm('选中的用户将会从当前科室移除。')
                        .then(confirmed => {
                            if (confirmed) {
                                abp.ajax({
                                    type: 'POST',
                                    url: `/api/depart-device-type/remove-many?depId=${vm.department.id}`,
                                    data: JSON.stringify(vm.depSelectedDeviceTypes)
                                }).then((res) => {
                                    if (res.code === 0) {
                                        abp.notify.success(res.msg);
                                        vm.loadDepDeviceTypes();
                                    }
                                });
                            }
                        });
                }
                else {
                    abp.notify.error("请选中要移除的用户。");
                }
            },

            // 移除单个设备类型
            remove(id) {
                var vm = this;
                abp.message.confirm('确定要移除当前设备类型？')
                    .then(confirmed => {
                        if (confirmed) {
                            abp.ajax({
                                type: 'get',
                                url: `/api/depart-device-type/remove-single?deviceTypeId=${id}&depId=${vm.department.id}`
                            }).then(res => {
                                if (res.code === 0) {
                                    abp.notify.success(res.msg);
                                    vm.loadDepDeviceTypes();
                                }
                            });
                        }
                    });
            },

            // 加载当前用户角色和权限.
            loadPermission() {
                var vm = this;
                return new Promise((resolve, reject) => {
                    if (abp.auth.isGranted('DeviceGroup.DepartmentDeviceTypes')) { // 科室用设备类型页面权限
                        vm.depDeviceTypePermission = true;
                        if (abp.auth.isGranted('DeviceGroup.DepartmentDeviceTypes.Add')) {// 添加现有设备类型
                            vm.depDeviceTypeAddPermission = true;
                        }

                        if (abp.auth.isGranted('DeviceGroup.DepartmentDeviceTypes.Remove')) { // 移除科室设备类型
                            vm.depDeviceTypeRemovePermission = true;
                        }

                        if (abp.auth.isGranted('DeviceGroup.DepartmentDeviceTypes.Create')) { // 创建科室设备类型
                            vm.depDeviceTypeCreatePermission = true;
                        }
                    }
                    if (abp.auth.isGranted('OthersGoup.Others.MuMultiDepartment')) {
                        vm.multiDepartmentPermission = true;
                    }
                    resolve();
                });
            },

            // 点击科室
            nodeClicked(node) {
                if (node.icon != 'fa fa-hospital') {
                    var vm = this;
                    vm.department = node;
                    vm.loadDepDeviceTypes(vm.department.id);
                }
            },

            // 创建科室用用户，表单重置
            resetCreateForm() {
                var vm = this;
                vm.$refs['creatDeviceTypeForm'].resetFields();
                vm.createDialogVisible = false;
                vm.deviceType.name = null;
                vm.deviceType.modality = null;
                vm.deviceType.code = null;
                vm.deviceType.outerCode = null;
                vm.deviceType.isActive = true;
            },

            init() {
                var vm = this;
                vm.loadPermission()
                    .then(() => {
                        vm.loadTreeData().then(() => {
                            vm.loadTableData();
                        });
                    });
            }
        },
        created() {
            var vm = this;
            vm.init();
        },
        mounted() {
        }
    });
});